package com.chg.mymvc.servlet;

import com.chg.mymvc.entity.News;
import com.chg.mymvc.service.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/selectnews")
public class SelectNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String name = req.getParameter("getlistbyname");

        System.out.println(name);
        NewsServiceImpl ns = new NewsServiceImpl();
        List<News> newslist = ns.getNewssByName(name);
        if(newslist!=null) {
            ArrayList<News> list = new ArrayList<>();
            for (News news : newslist) {
                list.add(news);

                System.out.println(list+"111111");
            }
            req.setAttribute("ilist", list);
            req.getRequestDispatcher("page/NewsListManagement.jsp").forward(req, resp);

        }

        else{
            ArrayList<Object> list = new ArrayList<>();
            News news1 = new News();

            list.add(news1);
            req.setAttribute("list",list);
            req.getRequestDispatcher("page/NewsListManagement.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
